package com.wwj.study.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class app {
    public static void main(String[] args) {
        try {
            final CountDownLatch countDownLatch=new CountDownLatch(1);

            ZooKeeper zooKeeper=new ZooKeeper("172.30.1.172:2181", 4000, new Watcher() {
                public void process(WatchedEvent event) {
                    if (Event.KeeperState.SyncConnected==event.getState()){
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
            System.out.println("zooKeeper.getState():"+zooKeeper.getState());

            Stat stat= new Stat();
            stat=zooKeeper.exists("/zk-wwj",false);

            if(stat==null){
                //ZooDefs.Ids.OPEN_ACL_UNSAFE 权限
                //CreateMode.PERSISTENT 持久化节点
                String zk= zooKeeper.create("/zk-wwj","0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                System.out.println("create zk:"+zk);
            }

            byte[] bytes= zooKeeper.getData("/zk-wwj",null,stat);
            System.out.println("zk-wwj value :"+new String(bytes));

            stat= zooKeeper.setData("/zk-wwj","1".getBytes(),0);

            System.out.println("stat.getVersion():"+stat.getVersion());

            zooKeeper.delete("/zk-wwj",stat.getVersion());

            zooKeeper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
